package com.wsd.smartcarwasher.service;

import com.alibaba.fastjson.JSONObject;
import com.wsd.smartcarwasher.dao.PriceTimeMapper;
import com.wsd.smartcarwasher.domain.Machine;
import com.wsd.smartcarwasher.domain.PriceTime;
import com.wsd.smartcarwasher.domain.PriceTimeExample;
import com.wsd.smartcarwasher.domain.PriceTimeModel;
import com.wsd.smartcarwasher.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PriceTimeService {

  @Autowired
  private PriceTimeMapper priceTimeMapper;
    @Autowired(required = false)
    private MachineService machineService;

    int insert(PriceTime priceTime)
    {
        return this.priceTimeMapper.insert(priceTime);
    }
    PriceTime findPriceTimeByPriceId(int priceId)
    {
        return this.priceTimeMapper.selectByPrimaryKey(priceId);
    }

    public List<PriceTime> queryPriceTimeAll(int machineId) {
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria()
                .andStatusEqualTo((byte)0)
                .andIsplatFormEqualTo((byte)0)
                .andMachineIdEqualTo(machineId);
        List<PriceTime> ls =this.priceTimeMapper.selectByExample(example);
        if(ls.isEmpty())
        {
            example=new PriceTimeExample();
            example.createCriteria()
                    .andStatusEqualTo((byte)0)
                    .andIsplatFormEqualTo((byte)1)
                    .andPartnerIdIsNotNull()
                    .andMachineIdEqualTo(machineId);
            ls =this.priceTimeMapper.selectByExample(example);
        }
        return ls;
    }
    public int updatePartnerPriceTime(PriceTime priceTime)
    {
        priceTime.setStatus(1);
        priceTime.setIsplatForm((byte)1);
       return this.priceTimeMapper.insert(priceTime);
    }

    public List<PriceTime> isStorePriceTime(int machineId) {
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria()
                .andIsplatFormEqualTo((byte)1)
                .andPartnerIdIsNotNull()
                .andMachineIdEqualTo(machineId);
        List<PriceTime> ls =this.priceTimeMapper.selectByExample(example);
        return ls;
    }

    public List<PriceTime> queryStorePriceTime(int machineId) {
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria().andStatusEqualTo((byte)0)
                .andIsplatFormEqualTo((byte)1)
                .andPartnerIdIsNotNull()
                .andMachineIdEqualTo(machineId);
        List<PriceTime> ls =this.priceTimeMapper.selectByExample(example);
        if(ls.isEmpty())
        {//为空，去查平台的价格
            example=new PriceTimeExample();
            example.createCriteria().andStatusEqualTo((byte)0)
                    .andIsplatFormEqualTo((byte)0)
                    .andMachineIdEqualTo(machineId);
            ls =this.priceTimeMapper.selectByExample(example);
            ls.get(0).setText("服从平台价格，即您的设备价格将服从平台的时段设定，若您不勾选，自己设定价格,需要注意的是,设定之后需要平台审核");
            ls.get(0).setPriceTimeModelList(this.covertPriceTime(ls.get(0).getType()));
            return ls;
        }
//        ls.get(0).setText("服从平台价格，即您的设备价格将服从平台的时段设定，若您不勾选，自己设定价格,需要注意的是,设定之后需要平台审核");
        ls.get(0).setPriceTimeModelList(this.covertPriceTime(ls.get(0).getType()));
        return ls;
    }

    public List<PriceTime> queryPartnerPriceTimeAll(int machineId) {
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria().andIsplatFormEqualTo((byte)1)
                .andPartnerIdIsNotNull()
                .andMachineIdEqualTo(machineId);
        List<PriceTime> ls =this.priceTimeMapper.selectByExample(example);
        if(ls.isEmpty())
        {
            return null;
        }
        for (PriceTime p: ls
             ) {
            p.setPriceTimeModelList(this.covertPriceTime(ls.get(0).getType()));
        }
        return ls;
    }
    public PriceTime queryPriceTimeStatus(int machineId) {
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria().andIsplatFormEqualTo((byte)1)
                .andPartnerIdIsNotNull()
                .andStatusEqualTo((byte)0)
                .andMachineIdEqualTo(machineId);
        List<PriceTime> ls =this.priceTimeMapper.selectByExample(example);

        if(ls.isEmpty())
        {
            return null;
        }
        return ls.get(0);
    }

    public int updateIsObeyPartner(byte status,Integer partnerId,Integer machineId,Integer priceTimeId)
    {

        int changes=this.priceTimeMapper.updateIsObeyPartner(status,partnerId,machineId,priceTimeId);

        return changes;
    }



    public PriceTime getPrice(int priceId) {
        PriceTime priceTime=this.priceTimeMapper.selectByPrimaryKey(priceId);
        return priceTime;
    }
   public int addPriceTime(PriceTime priceTime)
    {
//        priceTime.setCreate_time(new Date().toLocaleString());
        priceTime.setStatus(0);
        if(priceTime.getPartnerId()!=null)
        {
            priceTime.setIsplatForm((byte)1);
            priceTime.setStatus(1);
        }
        return priceTimeMapper.insert(priceTime);
    }


    public int updatePriceTime(PriceTime priceTime)
    {
        PriceTimeExample priceTimeExample=new PriceTimeExample();
        priceTimeExample.createCriteria().andMachineIdEqualTo(priceTime.getMachineId())
            .andIsplatFormEqualTo((byte)0)
                .andStatusEqualTo((byte)0);
        List<PriceTime> priceTimeList=this.priceTimeMapper.selectByExample(priceTimeExample);
        if(priceTimeList.isEmpty())
        {
            return 0;
        }
        priceTime.setIsplatForm((byte)0);
        priceTime.setPriceId(priceTimeList.get(0).getPriceId());
        priceTime.setStatus(0);
        return this.priceTimeMapper.updateByPrimaryKey(priceTime);
    }
    public int updateStorePriceTime(PriceTime priceTime)
    {

        priceTime.setIsplatForm((byte)1);
        priceTime.setStatus(1);

        return this.priceTimeMapper.insert(priceTime);
    }

 public int setAllPriceTime(PriceTime priceTime)
    {
        //删除所有的平台价格
        PriceTimeExample example=new PriceTimeExample();
        example.createCriteria().andIsplatFormEqualTo((byte)0)
                .andPartnerIdIsNotNull();
        if(!this.priceTimeMapper.selectByExample(example).isEmpty())
        {
            int changes=this.priceTimeMapper.deleteByExample(example);

        }else{
            List<Machine> machineList=this.machineService.getAllMachine();
            for (Machine machine:machineList
                 ) {
                priceTime.setMachineId(machine.getId());
                this.priceTimeMapper.insert(priceTime);
            }
        }
        return 1;
    }

    /**
     * 查询使用平台价格还是商家价格
     * @param machineId
     * @return
     */

    public Map<String, Object> isUsePlatPrice(int machineId) {
        Map<String,Object> node=new HashMap<>();
        PriceTimeExample example=new PriceTimeExample();
            example.createCriteria().andMachineIdEqualTo(machineId)
                    .andPartnerIdIsNotNull()
                    .andIsplatFormEqualTo((byte)1)
                    .andStatusEqualTo((byte)0);
            List<PriceTime> priceTimeList=this.priceTimeMapper.selectByExample(example);
            if(!priceTimeList.isEmpty())
            {
                node.put("priceTimes",priceTimeList.get(0).getType());
                node.put("machineId",priceTimeList.get(0).getMachineId());
                return node;
            }
            example=new PriceTimeExample();
            example.createCriteria().andMachineIdEqualTo(machineId).andPartnerIdIsNull().andIsplatFormEqualTo((byte)0)
                    .andStatusEqualTo((byte)0);
            priceTimeList=this.priceTimeMapper.selectByExample(example);
            node.put("priceTimes",priceTimeList.get(0).getType());
            node.put("machineId",priceTimeList.get(0).getMachineId());
            return node;
//        //根据设备id判断是否该设备为直营还是加盟
//        Machine machine = this.machineService.getMachineByMachineId(machineId);
//        if (machine == null)
//        {
//            return null;
//        }
//        //当机器为直营使用平台价格,0为直营
//        Map<String,Object> node=new HashMap<>();
//        if(machine.getIsDirect()==0)
//        {
//            PriceTimeExample example=new PriceTimeExample();
//            example.createCriteria().andMachineIdEqualTo(machineId)
//                    .andPartnerIdIsNull()
//                    .andIsplatFormEqualTo((byte)0)
//                    .andStatusEqualTo((byte)0);
//            List<PriceTime> priceTimeList=this.priceTimeMapper.selectByExample(example);
//            if(priceTimeList.isEmpty())
//            {
//                return null;
//            }
//            node.put("priceTimes",priceTimeList.get(0).getType());
//            node.put("machineId",priceTimeList.get(0).getMachineId());
////            node.put("typeName",priceTimeList.get(0).getTimeName());
////            return node;
//        }else{
//            //当机器为加盟时，先判断该机器是否存在听从商家配置的价格，如若没有，再去使用平台价格
//            PriceTimeExample example=new PriceTimeExample();
//            example.createCriteria().andMachineIdEqualTo(machineId)
//                    .andPartnerIdEqualTo(machine.getPartnerId())
//                    .andIsplatFormEqualTo((byte)1)
//                    .andStatusEqualTo((byte)0);
//            List<PriceTime> priceTimeList=this.priceTimeMapper.selectByExample(example);
//            if(priceTimeList.isEmpty())
//            {
//                //没有商家的信息，听从平台配置价格
//                PriceTimeExample isDirectexample=new PriceTimeExample();
//                isDirectexample.createCriteria().andMachineIdEqualTo(machineId)
//                        .andPartnerIdIsNull()
//                        .andIsplatFormEqualTo((byte)0)
//                        .andStatusEqualTo((byte)0);
//                List<PriceTime> isDirecteTimeList=this.priceTimeMapper.selectByExample(isDirectexample);
//
//                if(isDirecteTimeList.isEmpty())
//                {
//                    return null;
//                }
//
//                node.put("priceTimes",isDirecteTimeList.get(0).getType());
//                node.put("machineId",isDirecteTimeList.get(0).getMachineId());
////                node.put("typeName",priceTimeList.get(0).getTimeName());
////                return node;
//            }else{
//
//                node.put("priceTimes",priceTimeList.get(0).getType());
//                node.put("machineId",priceTimeList.get(0).getMachineId());
////                node.put("typeName",priceTimeList.get(0).getTimeName());
////                return node;
//            }
//        }
//            return node;
        }

    /**
     * 转化数据库的时间字段类型，合并后传递给H5
     * @param type
     * @return
     */
    public List<PriceTimeModel> covertPriceTime(String type) {

        JSONObject jsonObject = JSONObject.parseObject(type);
        List<PriceTimeModel> priceTimeModelList=new ArrayList<>();
        int a=1;
        int n=0;
        for (int i=0;i<24;i++)
        {
            if (jsonObject.getJSONObject(i+1+"").equals(jsonObject.getJSONObject(i+1+1+"")))
            {
                System.out.println(a);
                a++;
            continue;
            }else{
                PriceTimeModel priceTimeModel=new PriceTimeModel();
                priceTimeModel.setStartTime(n);
                priceTimeModel.setEndTime(i+1);
                Map<String,Object> map=new HashMap<>();
                map.put("A",jsonObject.getJSONObject(i+"").get("A"));
                map.put("B",jsonObject.getJSONObject(i+"").get("B"));
                map.put("C",jsonObject.getJSONObject(i+"").get("C"));
                priceTimeModel.setPrice(map);
                priceTimeModelList.add(priceTimeModel);
                n=i+1;
            }
        }
        return priceTimeModelList;
    }

    /**
     * 转化时间段价格为String类型
     * @param priceTimeModelList
     * @return
     */
    public String covertPriceTimetoString(List<PriceTimeModel> priceTimeModelList) {

        JSONObject price = new JSONObject(new LinkedHashMap());
        for (PriceTimeModel priceTimeModel:priceTimeModelList
             ) {
                for(int i=priceTimeModel.getStartTime();i<=priceTimeModel.getEndTime();i++)
                {
                    System.out.println(i);
                    Map<String,Object> map=new HashMap<>();
                    map.put("A",priceTimeModel.getPrice().get("A"));
                    map.put("B",priceTimeModel.getPrice().get("B"));
                    map.put("C",priceTimeModel.getPrice().get("C"));
                    price.put(i+"",map);
                }
        }
        return price.toString();
    }

    /**
     * 当前时间是否在适用时段内，返回值0为不在该时段
     * @param timeArray
     * @return
     */
    public int isUseCardTime(String [] timeArray) {
        Date s= DateUtil.convertStringToHour(timeArray[0]);
        Date e= DateUtil.convertStringToHour(timeArray[1]);
        SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        Date now=DateUtil.convertStringToHour(formatter.format(date));
        if(s.getTime()<now.getTime()&&now.getTime()<e.getTime())
        {
            return 0;
        }

        return 1;
    }

    public static void main(String[] args) {
        String [] timeArray=new  String []{"18:00:00","24:59:59"};
        Date s= DateUtil.convertStringToHour(timeArray[0]);
        Date e= DateUtil.convertStringToHour(timeArray[1]);
        SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        Date now=DateUtil.convertStringToHour(formatter.format(date));
        if(s.getTime()<now.getTime()&&now.getTime()<e.getTime())
        {
            System.out.println("0");
        }

        System.out.println("1");
    }

    /**
     * 根据现在时段匹配时段价格
     * @param node
     * @return
     */
    public Map<Integer,Object> matchingPrice(Map<String,Object> node)
       {
//            获取现在时段，且格式化成小时
           int nowHour=Integer.parseInt(DateUtil.format(DateUtil.getSysTime(),"HH"));
           if (nowHour==0)
           {
               nowHour=24;
           }
            JSONObject jsonObject = JSONObject.parseObject((String) node.get("priceTimes"));
            Map<Integer,Object> nodes=new HashMap<>();
            nodes.put(0,jsonObject.getJSONObject(String.valueOf(nowHour)).get("A"));
            nodes.put(1,jsonObject.getJSONObject(String.valueOf(nowHour)).get("B"));
            nodes.put(2,jsonObject.getJSONObject(String.valueOf(nowHour)).get("C"));
            return nodes;
       }
    public int restartPriceTime(Integer machineId)
    {
        PriceTime priceTime=new PriceTime();
        priceTime.setCreate_time(new Date().toLocaleString());
        priceTime.setMachineId(machineId);
        priceTime.setStatus(0);
        PriceTime Time=this.findPriceTimeByPriceId(0);
        priceTime.setType(Time.getType());
        priceTime.setIsplatForm((byte)0);

        return priceTimeMapper.insert(priceTime);
    }
}
